import React, { useState } from 'react';

const Tree = ({ data }) => {
  const [treeData, setTreeData] = useState(data);

  const handleMoveUp = (parentId, index) => {
    if (index === 0) return; // Already at the top
    const newData = [...treeData];
    const parent = newData.find((item) => item.id === parentId);
    const temp = parent.children[index];
    parent.children[index] = parent.children[index - 1];
    parent.children[index - 1] = temp;
    setTreeData(newData);
  };

  const handleMoveDown = (parentId, index) => {
    const newData = [...treeData];
    const parent = newData.find((item) => item.id === parentId);
    if (index === parent.children.length - 1) return; // Already at the bottom
    const temp = parent.children[index];
    parent.children[index] = parent.children[index + 1];
    parent.children[index + 1] = temp;
    setTreeData(newData);
  };

  const renderTree = (data) => {
    return data.map((item) => (
      <div key={item.id} style={{ marginLeft: item.level * 20 }}>
        <div>{item.name}</div>
        <div>
          <button onClick={() => handleMoveUp(item.parentId, item.index)}>Up</button>
          <button onClick={() => handleMoveDown(item.parentId, item.index)}>Down</button>
        </div>
        {item.children && renderTree(item.children)}
      </div>
    ));
  };

  return <div>{renderTree(treeData)}</div>;
};

const data = [
  {
    id: 1,
    name: 'Div 1',
    parentId: null,
    level: 0,
    index: 0,
    children: [
      {
        id: 2,
        name: 'Div 1.1',
        parentId: 1,
        level: 1,
        index: 0,
        children: [
          {
            id: 3,
            name: 'Div 1.1.1',
            parentId: 2,
            level: 2,
            index: 0,
            children: [],
          },
        ],
      },
      {
        id: 4,
        name: 'Div 1.2',
        parentId: 1,
        level: 1,
        index: 1,
        children: [],
      },
    ],
  },
  {
    id: 5,
    name: 'Div 2',
    parentId: null,
    level: 0,
    index: 1,
    children: [],
  },
];

const App = () => {
  return (
    <div>
      <h1>Tree</h1>
      <Tree data={data} />
    </div>
  );
};

export default App;
